<template>
  <scroll-view
    scroll-x
    class="bg-white nav"
    :class="computedNavTabBarClassNames"
    scroll-with-animation
    :scroll-left="scrollLeft"
  >
    <view class="flex text-center">
      <view
        class="cu-item flex-sub"
        :class="item.key === curPickedTabKey ? 'text-green cur' : ''"
        v-for="(item, idx) in tabItems"
        :key="item.key"
        @click="onPickedTab(item, idx)"
      >
        {{ item.title }}
      </view>
    </view>
  </scroll-view>
</template>
<script setup>
import { ref, watch,computed } from "vue";
const props = defineProps({
  tabItems: {
    type: Array,
    validator(prop) {
      if (Array.isArray(prop) && prop.length > 0) {
        return prop.every(
          (el) => el.hasOwnProperty("title") && el.hasOwnProperty("key")
        );
      }else if(Array.isArray(prop) && prop.length === 0){
          return true;
      } else {
        return false;
      }
    },
  },
  curPickedTabKey: {
    type: String || Number,
    default: "",
  },
  isFixedTop:{
      type:Boolean,
      default:true
  }
});

const scrollLeft = ref(0);

const emits = defineEmits(["update:curPickedTabKey","change"]);
const onPickedTab = (item, idx) => {
  emits("update:curPickedTabKey", item.key);
  emits("change",item);
  scrollLeft.value = idx * 60;
};

watch(
  () => props.curPickedTabKey,
  (newVal, oldVal) => {
    if (props.tabItems.length > 0) {
      const curPickedTabIdx = props.tabItems.findIndex(
        (el) => el.key === newVal
      );
      onPickedTab(props.tabItems[curPickedTabIdx], curPickedTabIdx);
    }
  },
  { immediate: true }
);
const computedNavTabBarClassNames = computed(()=>{
    //return []
    return props.isFixedTop ? ["fixed","fixed-top"] : []
})
</script>
<style>
.nav.fixed.fixed-top{
    top:var(--window-top)
}
</style>
